<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <PageHeader
      title="主机组管理"
      subtitle="管理和组织您的主机资源"
      icon="fa fa-object-group"
    />

    <!-- 操作栏 -->
    <PageToolbar>
      <template #left>
        <el-button v-permission="'write'" type="primary" @click="showCreateDialog = true" class="tech-button">
          <i class="fa fa-plus"></i> 新建主机组
        </el-button>

        <!-- 视图切换按钮 -->
        <el-button-group class="view-toggle">
          <el-button
            :type="viewMode === 'card' ? 'primary' : ''"
            @click="changeViewMode('card')"
            class="tech-button"
          >
            <i class="fa fa-th-large"></i> 卡片视图
          </el-button>
          <el-button
            :type="viewMode === 'table' ? 'primary' : ''"
            @click="changeViewMode('table')"
            class="tech-button"
          >
            <i class="fa fa-table"></i> 表格视图
          </el-button>
        </el-button-group>
      </template>
      <template #right>
        <el-input
          v-model="searchQuery"
          placeholder="搜索主机组..."
          style="width: 300px"
          @input="handleSearch"
          class="tech-input"
        >
          <template #prefix>
            <i class="fa fa-search"></i>
          </template>
        </el-input>

        <el-select
          v-model="environmentFilter"
          placeholder="环境筛选"
          style="width: 120px; margin-left: 10px"
          @change="handleFilter"
          class="tech-input"
          key="toolbar-env-select"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="开发环境" value="dev"></el-option>
          <el-option label="测试环境" value="test"></el-option>
          <el-option label="预发布环境" value="staging"></el-option>
          <el-option label="生产环境" value="prod"></el-option>
        </el-select>

        <el-button @click="refreshData" class="tech-button">
          <i class="fa fa-refresh"></i> 刷新
        </el-button>
      </template>
    </PageToolbar>

    <!-- 卡片视图 -->
    <div v-if="viewMode === 'card'" class="host-groups-grid">
      <div
        v-for="group in hostGroups"
        :key="group?.id || `group-${Math.random()}`"
        class="host-group-card"
        @click="viewGroupDetail(group)"
      >
        <div class="card-header">
          <div class="group-info">
            <h3>{{ group.name }}</h3>
            <span class="environment-tag" :class="group.environment">
              {{ group.environment_display }}
            </span>
          </div>
          <div class="card-actions" @click.stop>
            <el-dropdown trigger="click">
              <el-button link size="small">
                <i class="fa fa-ellipsis-v"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-permission="'write'" @click="editGroup(group)">
                    <i class="fa fa-edit"></i> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click="manageHosts(group)">
                    <i class="fa fa-server"></i> 管理主机
                  </el-dropdown-item>
                  <el-dropdown-item v-permission="'write'" @click="deleteGroup(group)" divided>
                    <i class="fa fa-trash"></i> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <div class="card-content">
          <p class="description">{{ group.description || '暂无描述' }}</p>

          <div class="stats">
            <div class="stat-item">
              <i class="fa fa-server"></i>
              <span>{{ group.host_count }} 台主机</span>
            </div>
            <div class="stat-item">
              <i class="fa fa-check-circle" style="color: #67c23a"></i>
              <span>{{ group.online_host_count }} 在线</span>
            </div>
          </div>

          <div class="tags" v-if="group.tags">
            <el-tag
              v-for="tag in group.tags.split(',')"
              :key="tag"
              size="small"
              style="margin-right: 5px"
            >
              {{ tag.trim() }}
            </el-tag>
          </div>
        </div>

        <div class="card-footer">
          <div class="owner-info">
            <i class="fa fa-user"></i>
            <span>{{ getOwnerDisplayName(group) }}</span>
          </div>
          <div class="create-time">
            <i class="fa fa-clock-o"></i>
            <span>{{ formatDate(group.created_at) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 表格视图 -->
    <div v-if="viewMode === 'table'" class="host-groups-table">
      <el-table
        :data="hostGroups"
        v-loading="loading"
        class="glass-dialog tech-table"
        stripe
        border
        style="width: 100%;"
      >
        <el-table-column prop="name" label="主机组名称" min-width="200">
          <template #default="scope">
            <div class="group-name-cell">
              <span class="group-name">{{ scope.row.name }}</span>
              <span class="environment-tag" :class="scope.row.environment">
                {{ scope.row.environment_display }}
              </span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述" min-width="200">
          <template #default="scope">
            <span>{{ scope.row.description || '暂无描述' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="host_count" label="主机数量" width="100" align="center">
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.host_count || 0 }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="online_host_count" label="在线主机" width="100" align="center">
          <template #default="scope">
            <el-tag size="small" type="success">{{ scope.row.online_host_count || 0 }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="owner_name" label="负责人" width="120">
          <template #default="scope">
            <span>{{ getOwnerDisplayName(scope.row) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.created_at) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="380" fixed="right" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                size="default"
                type="primary"
                @click="editGroup(scope.row)"
                class="action-btn glass-button"
                v-permission="'write'"
              >
                <i class="fa fa-edit"></i> 编辑
              </el-button>
              <el-button
                size="default"
                type="info"
                @click="viewGroupDetail(scope.row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-server"></i> 主机
              </el-button>
              <el-button
                size="default"
                type="danger"
                @click="deleteGroup(scope.row)"
                class="action-btn glass-button"
                v-permission="'write'"
              >
                <i class="fa fa-trash"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && hostGroups.length === 0" class="empty-state">
      <i class="fa fa-object-group"></i>
      <h3>暂无主机组</h3>
      <p>点击上方按钮创建您的第一个主机组</p>
    </div>

    <!-- 创建/编辑主机组对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingGroup ? '编辑主机组' : '创建主机组'"
      width="600px"
      class="tech-dialog"
      @close="handleDialogClose"
    >
      <el-form :model="groupForm" :rules="groupRules" ref="groupFormRef" label-width="100px" class="tech-form">
        <el-form-item label="主机组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入主机组名称" class="tech-input"></el-input>
        </el-form-item>

        <el-form-item label="环境" prop="environment">
          <el-select
            v-model="groupForm.environment"
            placeholder="请选择环境"
            class="tech-input dialog-select"
            style="width: 100%"
            @change="handleEnvironmentChange"
          >
            <el-option label="开发环境" value="dev"></el-option>
            <el-option label="测试环境" value="test"></el-option>
            <el-option label="预发布环境" value="staging"></el-option>
            <el-option label="生产环境" value="prod"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" prop="owner">
          <el-select
            v-model="groupForm.owner"
            placeholder="请选择负责人"
            filterable
            clearable
            @change="handleOwnerChange"
            class="tech-input dialog-select"
            style="width: 100%"
          >
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="getUserDisplayName(user)"
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="标签">
          <el-input v-model="groupForm.tags" placeholder="多个标签用逗号分隔" class="tech-input"></el-input>
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="groupForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入主机组描述"
            class="tech-input"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCreateDialog = false" class="tech-button">取消</el-button>
        <el-button type="primary" @click="saveGroup" :loading="saving" class="tech-button">
          {{ editingGroup ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 主机列表对话框 -->
    <el-dialog
      v-model="showHostListDialog"
      :title="`主机组「${selectedGroupName}」的主机列表`"
      width="900px"
      class="tech-dialog"
    >
      <el-table
        :data="groupHosts"
        v-loading="loadingHosts"
        class="glass-dialog tech-table"
        stripe
        border
        style="width: 100%;"
      >
        <el-table-column prop="hostname" label="主机名" width="150">
          <template #default="scope">
            <div class="hostname-cell">
              <i class="fa fa-server" style="color: #00eaff; margin-right: 8px;"></i>
              <span>{{ scope.row.hostname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="public_ip" label="公网IP" width="130" />
        <el-table-column prop="private_ip" label="内网IP" width="130">
          <template #default="scope">
            <span v-if="scope.row.private_ip && scope.row.private_ip !== '-'">{{ scope.row.private_ip }}</span>
            <span v-else class="no-data">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="120" align="center">
          <template #default="scope">
            <el-tag size="small" :type="getHostTypeTagType(scope.row.type)">
              {{ getHostTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <div class="status-cell">
              <div :class="['status-indicator', scope.row.status]"></div>
              <span>{{ scope.row.status === 'online' ? '在线' : '离线' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="openSSH(scope.row)" class="action-btn">
                <i class="fa fa-terminal"></i>
              </el-button>
              <el-button type="info" size="small" @click="viewHostDetail(scope.row)" class="action-btn">
                <i class="fa fa-info-circle"></i>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="!loadingHosts && groupHosts.length === 0" class="empty-state" style="padding: 40px 20px;">
        <i class="fa fa-server" style="font-size: 3rem; color: #00eaff; opacity: 0.6; margin-bottom: 15px;"></i>
        <h4>该主机组暂无主机</h4>
        <p>可以在主机管理页面将主机分配到此主机组</p>
      </div>

      <template #footer>
        <el-button @click="showHostListDialog = false" class="tech-button">关闭</el-button>
        <el-button type="primary" @click="goToHostManagement" class="tech-button">
          <i class="fa fa-external-link"></i> 前往主机管理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import PageHeader from '@/components/PageHeader.vue'
import PageToolbar from '@/components/PageToolbar.vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()

// 响应式数据
const hostGroups = ref([])
const users = ref([])
const searchQuery = ref('')
const environmentFilter = ref('')
const showCreateDialog = ref(false)
const editingGroup = ref(null)
const saving = ref(false)
const viewMode = ref('table') // 'card' 或 'table'，默认表格视图
const loading = ref(false)
const showHostListDialog = ref(false)
const loadingHosts = ref(false)
const groupHosts = ref([])
const selectedGroupName = ref('')

// 表单数据
const groupForm = reactive({
  name: '',
  environment: 'dev',
  owner: null,
  tags: '',
  description: ''
})

// 监听表单数据变化
watch(groupForm, (newVal) => {
  console.log('表单数据变化:', newVal)
}, { deep: true })

// 表单验证规则
const groupRules = {
  name: [
    { required: true, message: '请输入主机组名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        if (!value || !groupForm.environment) return callback()

        // 检查在同一环境下主机组名称的唯一性
        const existingGroup = hostGroups.value.find(group =>
          group.name === value &&
          group.environment === groupForm.environment &&
          (!editingGroup.value || group.id !== editingGroup.value.id)
        )

        if (existingGroup) {
          const envNames = {
            'dev': '开发环境',
            'test': '测试环境',
            'staging': '预发布环境',
            'prod': '生产环境'
          }
          const envName = envNames[groupForm.environment] || groupForm.environment
          callback(new Error(`在${envName}中已存在同名主机组，请使用其他名称`))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  environment: [
    { required: true, message: '请选择环境', trigger: 'change' }
  ]
  // owner字段不是必填的，所以不需要验证规则
}

const groupFormRef = ref()
const ownerSelectRef = ref()

// 方法
const fetchHostGroups = async () => {
  try {
    const params = {}
    if (searchQuery.value) params.search = searchQuery.value
    if (environmentFilter.value) params.environment = environmentFilter.value

    const response = await axios.get('/api/hostgroups/', { params })
    console.log('主机组API响应:', response.data)

    // 处理分页响应或直接数组响应
    let groupData = response.data
    if (groupData && typeof groupData === 'object' && groupData.results) {
      // 分页响应
      groupData = groupData.results
    }

    // 确保是数组并过滤掉无效的主机组数据
    if (Array.isArray(groupData)) {
      hostGroups.value = groupData.filter(group => group && group.id)
      console.log('过滤后的主机组列表:', hostGroups.value.length, '个主机组')
    } else {
      console.warn('主机组数据不是数组格式:', groupData)
      hostGroups.value = []
    }
  } catch (error) {
    console.error('获取主机组失败:', error)
    ElMessage.error('获取主机组失败')
    hostGroups.value = []
  }
}

const fetchUsers = async () => {
  try {
    // 获取所有角色
    const rolesResponse = await axios.get('/api/roles/')
    let allRoles = rolesResponse.data
    if (allRoles && typeof allRoles === 'object' && allRoles.results) {
      allRoles = allRoles.results
    }

    // 查找部门领导角色
    const departmentLeaderRole = allRoles.find(role =>
      role.name === '部门领导' ||
      role.name.includes('部门领导') ||
      role.name.includes('领导')
    )

    if (departmentLeaderRole) {
      // 获取所有用户组
      const groupsResponse = await axios.get('/api/groups/')
      let allGroups = groupsResponse.data
      if (allGroups && typeof allGroups === 'object' && allGroups.results) {
        allGroups = allGroups.results
      }

      // 查找关联了部门领导角色的用户组
      const leaderGroups = allGroups.filter(group => {
        if (!group || !group.roles || !Array.isArray(group.roles)) {
          return false
        }
        return group.roles.some(role => role.id === departmentLeaderRole.id)
      })

      // 获取这些用户组的用户
      if (leaderGroups.length > 0) {
        let allLeaderUsers = []

        for (const group of leaderGroups) {
          try {
            const response = await axios.get(`/api/groups/${group.id}/members/`)
            let groupUsers = response.data
            if (groupUsers && typeof groupUsers === 'object' && groupUsers.results) {
              groupUsers = groupUsers.results
            }

            if (Array.isArray(groupUsers)) {
              allLeaderUsers = allLeaderUsers.concat(groupUsers)
            }
          } catch (error) {
            console.error(`获取用户组 ${group.name} 用户失败:`, error)
          }
        }

        // 去重（根据用户ID）
        const uniqueUsers = []
        const userIds = new Set()

        for (const user of allLeaderUsers) {
          if (user && user.id && !userIds.has(user.id)) {
            userIds.add(user.id)
            uniqueUsers.push(user)
          }
        }

        // 过滤掉无效的用户数据
        users.value = uniqueUsers.filter(user => user && user.id && user.username)
      } else {
        users.value = []
      }

    } else {
      // 回退到获取所有用户
      const allUsersResponse = await axios.get('/api/users/')
      let allUsers = allUsersResponse.data
      if (allUsers && typeof allUsers === 'object' && allUsers.results) {
        allUsers = allUsers.results
      }

      if (Array.isArray(allUsers)) {
        users.value = allUsers.filter(user => user && user.id && user.username)
      } else {
        users.value = []
      }
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    users.value = []
  }
}

const refreshData = () => {
  fetchHostGroups()
}

// 视图模式切换
const changeViewMode = (mode) => {
  viewMode.value = mode
  // 保存到localStorage
  localStorage.setItem('hostGroupViewMode', mode)
}

const handleSearch = () => {
  fetchHostGroups()
}

const handleFilter = () => {
  fetchHostGroups()
}

// 环境变化时重新验证主机组名称
const handleEnvironmentChange = () => {
  // 如果已经输入了主机组名称，重新验证唯一性
  if (groupForm.name && groupFormRef.value) {
    groupFormRef.value.validateField('name')
  }
}

const resetForm = () => {
  Object.assign(groupForm, {
    name: '',
    environment: 'dev',
    owner: null,
    tags: '',
    description: ''
  })
  editingGroup.value = null

  // 清除表单验证
  if (groupFormRef.value) {
    groupFormRef.value.clearValidate()
  }
}

const editGroup = (group) => {
  console.log('编辑主机组数据:', group)
  console.log('当前用户列表:', users.value)

  editingGroup.value = group
  groupForm.name = group.name
  groupForm.environment = group.environment

  // 修复负责人设置逻辑
  if (group.owner && users.value.length > 0) {
    // 检查负责人ID是否在当前用户列表中
    const ownerExists = users.value.some(user => user.id === group.owner)
    if (ownerExists) {
      groupForm.owner = group.owner
      console.log('设置负责人ID:', group.owner)
    } else {
      console.warn('负责人ID不在当前用户列表中:', group.owner)
      groupForm.owner = null
    }
  } else {
    groupForm.owner = null
  }

  groupForm.tags = group.tags || ''
  groupForm.description = group.description || ''

  console.log('设置后的表单数据:', groupForm)
  showCreateDialog.value = true

  // 对话框打开后修复下拉菜单宽度
  setTimeout(() => {
    fixDropdownWidth()
  }, 100)
}

const saveGroup = async () => {
  if (!groupFormRef.value) return

  try {
    await groupFormRef.value.validate()
    saving.value = true

    // 清理数据，移除空值
    const data = {
      name: groupForm.name,
      environment: groupForm.environment,
      description: groupForm.description || '',
      tags: groupForm.tags || '',
      is_active: true
    }

    // 只有选择了负责人才添加owner字段
    if (groupForm.owner) {
      data.owner = groupForm.owner
    }

    console.log('保存主机组数据:', data)
    console.log('原始表单数据:', groupForm)

    if (editingGroup.value) {
      const response = await axios.put(`/api/hostgroups/${editingGroup.value.id}/`, data)
      console.log('更新主机组响应:', response.data)
      ElMessage.success('主机组更新成功')
    } else {
      const response = await axios.post('/api/hostgroups/', data)
      console.log('创建主机组响应:', response.data)
      ElMessage.success('主机组创建成功')
    }

    showCreateDialog.value = false
    resetForm()
    fetchHostGroups()
  } catch (error) {
    console.error('保存主机组失败:', error)
    if (error.response && error.response.data) {
      console.error('错误详情:', error.response.data)
      console.error('HTTP状态码:', error.response.status)
      console.error('请求URL:', error.response.config?.url)
      console.error('请求数据:', error.response.config?.data)

      // 处理验证错误
      if (error.response.data && typeof error.response.data === 'object') {
        const errors = error.response.data
        let errorMessage = '保存失败：'

        if (errors.name && Array.isArray(errors.name)) {
          errorMessage += errors.name.join(', ')
        } else if (errors.non_field_errors && Array.isArray(errors.non_field_errors)) {
          errorMessage += errors.non_field_errors.join(', ')
        } else {
          errorMessage += JSON.stringify(errors)
        }

        ElMessage.error(errorMessage)
      } else {
        const errorMsg = typeof error.response.data === 'string'
          ? error.response.data
          : JSON.stringify(error.response.data)
        ElMessage.error(`保存主机组失败: ${errorMsg}`)
      }
    } else {
      ElMessage.error('保存主机组失败')
    }
  } finally {
    saving.value = false
  }
}

const deleteGroup = async (group) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除主机组 "${group.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await axios.delete(`/api/hostgroups/${group.id}/`)
    ElMessage.success('主机组删除成功')
    fetchHostGroups()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除主机组失败:', error)
      ElMessage.error('删除主机组失败')
    }
  }
}

const viewGroupDetail = async (group) => {
  // 显示主机列表对话框
  selectedGroupName.value = group.name
  showHostListDialog.value = true
  await fetchGroupHosts(group.id)
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const getUserDisplayName = (user) => {
  if (!user) {
    return '未知用户'
  }

  // 检查用户数据的完整性
  if (!user.id || !user.username) {
    return '数据异常'
  }

  // 优先显示中文名，如果没有则显示用户名
  const displayName = user.chinese_name && user.chinese_name.trim() !== ''
    ? user.chinese_name
    : user.username

  return displayName || '未知用户'
}

const getOwnerDisplayName = (group) => {
  if (!group) return '未设置负责人'

  // 检查是否有负责人ID
  if (!group.owner) {
    return '未设置负责人'
  }

  // 优先显示中文名，如果中文名为空或null则显示用户名
  if (group.owner_chinese_name &&
      group.owner_chinese_name !== 'null' &&
      group.owner_chinese_name !== null &&
      group.owner_chinese_name.trim() !== '') {
    return group.owner_chinese_name
  }

  // 如果有owner_name字段则使用它
  if (group.owner_name && group.owner_name.trim() !== '') {
    return group.owner_name
  }

  return '未知负责人'
}

const handleOwnerChange = (value) => {
  groupForm.owner = value
}

// 处理对话框关闭
const handleDialogClose = () => {
  // 简单的重置，不强制删除DOM
  resetForm()
}

// 获取主机组的主机列表
const fetchGroupHosts = async (groupId) => {
  try {
    loadingHosts.value = true
    // 尝试使用主机组详情API获取主机列表
    const response = await axios.get(`/api/hostgroups/${groupId}/`)

    // 从主机组详情中获取主机列表
    if (response.data && response.data.hosts) {
      groupHosts.value = response.data.hosts.filter(host => host && host.id)
    } else {
      // 如果主机组详情API没有主机列表，尝试使用主机API筛选
      const hostResponse = await axios.get('/api/hosts/')

      let allHosts = hostResponse.data
      if (allHosts && typeof allHosts === 'object' && allHosts.results) {
        allHosts = allHosts.results
      }

      if (Array.isArray(allHosts)) {
        // 筛选属于该主机组的主机
        groupHosts.value = allHosts.filter(host => {
          return host && host.id && host.host_groups &&
                 host.host_groups.includes(parseInt(groupId))
        })
      } else {
        groupHosts.value = []
      }
    }
  } catch (error) {
    console.error('获取主机组主机列表失败:', error)
    ElMessage.error('获取主机列表失败')
    groupHosts.value = []
  } finally {
    loadingHosts.value = false
  }
}

// 获取主机类型文本
const getHostTypeText = (type) => {
  const typeMap = {
    'web': 'Web服务器',
    'db': '数据库',
    'app': '应用服务器',
    'cache': '缓存服务器',
    'other': '其他'
  }
  return typeMap[type] || type
}

// 获取主机类型标签类型
const getHostTypeTagType = (type) => {
  const typeMap = {
    'web': 'primary',
    'db': 'success',
    'app': 'warning',
    'cache': 'danger',
    'other': 'info'
  }
  return typeMap[type] || 'info'
}

// 打开SSH终端
const openSSH = async (host) => {
  try {
    const response = await axios.post('/api/ssh/request-access/', {
      host_id: host.id
    })

    if (response.data.success) {
      router.push(`/ssh/${host.id}?token=${response.data.access_token}`)
    } else {
      ElMessage.error(response.data.message || '无权访问此主机')
    }
  } catch (error) {
    console.error('请求SSH访问失败:', error)
    ElMessage.error('请求SSH访问失败')
  }
}

// 查看主机详情
const viewHostDetail = (host) => {
  // 跳转到主机管理页面并显示该主机的详情
  router.push({
    path: '/cmdb/hosts',
    query: {
      view_host: host.id
    }
  })
}

// 前往主机管理页面
const goToHostManagement = () => {
  showHostListDialog.value = false
  router.push('/cmdb/hosts')
}

// 生命周期
onMounted(() => {
  // 从localStorage读取用户的视图偏好
  const savedViewMode = localStorage.getItem('hostGroupViewMode')
  if (savedViewMode && (savedViewMode === 'card' || savedViewMode === 'table')) {
    viewMode.value = savedViewMode
  }

  fetchHostGroups()
  fetchUsers()
})
</script>

<style lang="scss" scoped>
// 主机组管理页面容器样式 - 与主机管理页面保持一致的深色调
.page-container {
  background: linear-gradient(135deg, #0f1327 0%, #1a2332 100%);
  min-height: 100vh;
  color: #e6e6e6;
}

// 视图切换按钮样式
.view-toggle {
  margin-left: 15px;

  .el-button {
    border-radius: 0 !important;

    &:first-child {
      border-top-left-radius: 8px !important;
      border-bottom-left-radius: 8px !important;
    }

    &:last-child {
      border-top-right-radius: 8px !important;
      border-bottom-right-radius: 8px !important;
    }
  }
}

// 表格视图样式
.host-groups-table {
  .group-name-cell {
    display: flex;
    align-items: center;
    justify-content: space-between; // 左右分布
    min-height: 32px;
    width: 100%;

    .group-name {
      font-weight: 500;
      color: white;
      white-space: nowrap;
      flex: 1; // 占据剩余空间
      min-width: 0; // 允许收缩
      overflow: hidden;
      text-overflow: ellipsis; // 超长显示省略号
    }

    .environment-tag {
      flex-shrink: 0; // 防止环境标签被压缩
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 60px;
      height: 24px;
      line-height: 1;
      margin-left: 8px; // 与组名保持间距
    }
  }

  // 操作按钮样式使用全局的action-buttons类
}

// 强制覆盖对话框中的选择框样式
.el-dialog {
  .el-select {
    .el-input__wrapper {
      background: rgba(255, 255, 255, 0.05) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      backdrop-filter: blur(10px) !important;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

      &:hover {
        border-color: rgba(0, 234, 255, 0.3) !important;
      }

      &.is-focus {
        border-color: #00eaff !important;
        box-shadow:
          inset 0 1px 3px rgba(0, 0, 0, 0.1),
          0 0 10px rgba(0, 234, 255, 0.3) !important;
      }

      .el-input__inner {
        color: white !important;
        background: transparent !important;

        &::placeholder {
          color: rgba(255, 255, 255, 0.5) !important;
        }
      }

      .el-input__suffix {
        .el-input__suffix-inner {
          .el-select__caret {
            color: rgba(255, 255, 255, 0.6) !important;

            &:hover {
              color: #00eaff !important;
            }
          }
        }
      }
    }
  }
}

// 下拉菜单样式已移除，由各页面自定义

// 工具栏中的选择框样式
.page-container {
  .el-select {
    .el-input__wrapper {
      background: rgba(255, 255, 255, 0.05) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      backdrop-filter: blur(10px) !important;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

      &:hover {
        border-color: rgba(0, 234, 255, 0.3) !important;
      }

      &.is-focus {
        border-color: #00eaff !important;
        box-shadow:
          inset 0 1px 3px rgba(0, 0, 0, 0.1),
          0 0 10px rgba(0, 234, 255, 0.3) !important;
      }

      .el-input__inner {
        color: white !important;
        background: transparent !important;

        &::placeholder {
          color: rgba(255, 255, 255, 0.5) !important;
        }
      }

      .el-input__suffix {
        .el-input__suffix-inner {
          .el-select__caret {
            color: rgba(255, 255, 255, 0.6) !important;

            &:hover {
              color: #00eaff !important;
            }
          }
        }
      }
    }
  }
}

// 主机组网格布局

.host-groups-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.host-group-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
  color: white;

  &:hover {
    transform: translateY(-5px);
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(0, 234, 255, 0.3);
    box-shadow:
      0 12px 40px rgba(0, 0, 0, 0.15),
      0 0 20px rgba(0, 234, 255, 0.2),
      inset 0 1px 0 rgba(255, 255, 255, 0.2);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;

  .group-info h3 {
    margin: 0 0 5px 0;
    color: white;
    font-size: 1.2rem;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
}

.environment-tag {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  color: white;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);

  &.dev {
    background: linear-gradient(135deg, #409eff, #5dade2);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }
  &.test {
    background: linear-gradient(135deg, #67c23a, #82e7ab);
    box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
  }
  &.staging {
    background: linear-gradient(135deg, #e6a23c, #f4d03f);
    box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
  }
  &.prod {
    background: linear-gradient(135deg, #f56c6c, #ff7675);
    box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
  }
}

.stats {
  display: flex;
  gap: 15px;
  margin: 15px 0;

  .stat-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 0.9rem;
    color: rgba(255, 255, 255, 0.8);

    i {
      color: #00eaff;
      text-shadow: 0 0 5px rgba(0, 234, 255, 0.5);
    }
  }
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  font-size: 0.8rem;
  color: rgba(255, 255, 255, 0.7);

  .owner-info, .create-time {
    display: flex;
    align-items: center;
    gap: 5px;

    i {
      color: #00eaff;
      text-shadow: 0 0 5px rgba(0, 234, 255, 0.5);
    }
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: white;

  i {
    font-size: 4rem;
    margin-bottom: 20px;
    opacity: 0.6;
    color: #00eaff;
    text-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
  }

  h3 {
    margin-bottom: 10px;
    font-size: 1.5rem;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }

  p {
    opacity: 0.8;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  }
}

// 对话框样式覆盖
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(20px) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  .el-dialog__header {
    background: transparent !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;

    .el-dialog__title {
      color: white !important;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3) !important;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: rgba(255, 255, 255, 0.8) !important;

      &:hover {
        color: #00eaff !important;
      }
    }
  }

  .el-dialog__body {
    background: transparent !important;
    color: white !important;
  }

  .el-dialog__footer {
    background: transparent !important;
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
  }
}

// 表单样式
:deep(.el-form) {
  .el-form-item__label {
    color: rgba(255, 255, 255, 0.9) !important;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
  }

  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focus {
      border-color: #00eaff !important;
      box-shadow:
        inset 0 1px 3px rgba(0, 0, 0, 0.1),
        0 0 10px rgba(0, 234, 255, 0.3) !important;
    }

    .el-input__inner {
      color: white !important;
      background: transparent !important;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
      }
    }
  }

  .el-select {
    .el-input__wrapper {
      background: rgba(255, 255, 255, 0.05) !important;
      border: 1px solid rgba(255, 255, 255, 0.1) !important;
      backdrop-filter: blur(10px) !important;
      box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

      &:hover {
        border-color: rgba(0, 234, 255, 0.3) !important;
      }

      &.is-focus {
        border-color: #00eaff !important;
        box-shadow:
          inset 0 1px 3px rgba(0, 0, 0, 0.1),
          0 0 10px rgba(0, 234, 255, 0.3) !important;
      }

      .el-input__inner {
        color: white !important;
        background: transparent !important;

        &::placeholder {
          color: rgba(255, 255, 255, 0.5) !important;
        }
      }

      .el-input__suffix {
        .el-input__suffix-inner {
          .el-select__caret {
            color: rgba(255, 255, 255, 0.6) !important;

            &:hover {
              color: #00eaff !important;
            }
          }
        }
      }
    }

    .el-select__placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }
  }

  .el-textarea__inner {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    color: white !important;
    backdrop-filter: blur(10px) !important;

    &::placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &:focus {
      border-color: #00eaff !important;
      box-shadow: 0 0 10px rgba(0, 234, 255, 0.3) !important;
    }
  }
}

// 按钮样式
:deep(.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: white !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, #00eaff, #0099cc) !important;
    border-color: #00eaff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, #33f0ff, #00b8e6) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }
}

// 下拉框样式已移除，由各页面自定义

// 标签样式
:deep(.el-tag) {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: white !important;
  backdrop-filter: blur(10px) !important;
}

// 专门针对页面中所有选择框的样式
:deep(.action-bar .el-select),
:deep(.el-form .el-select) {
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focus {
      border-color: #00eaff !important;
      box-shadow:
        inset 0 1px 3px rgba(0, 0, 0, 0.1),
        0 0 10px rgba(0, 234, 255, 0.3) !important;
    }

    .el-input__inner {
      color: white !important;
      background: transparent !important;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
      }
    }

    .el-input__suffix {
      .el-input__suffix-inner {
        .el-select__caret {
          color: rgba(255, 255, 255, 0.6) !important;

          &:hover {
            color: #00eaff !important;
          }
        }
      }
    }
  }

  .el-select__placeholder {
    color: rgba(255, 255, 255, 0.5) !important;
  }
}

// 下拉菜单样式已移除，由各页面自定义

// 下拉菜单箭头样式保留，用于工具栏下拉菜单
:deep(.el-dropdown-menu) {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
  border-radius: 12px !important;

  .el-dropdown-menu__item {
    color: rgba(255, 255, 255, 0.9) !important;
    background: transparent !important;
    border-radius: 8px !important;
    margin: 2px 6px !important;
    padding: 8px 12px !important;
    transition: all 0.3s ease !important;

    &:hover {
      background: rgba(0, 234, 255, 0.15) !important;
      color: white !important;
      transform: translateX(2px) !important;
      box-shadow: 0 2px 8px rgba(0, 234, 255, 0.2) !important;
    }

    i {
      color: rgba(0, 234, 255, 0.8) !important;
      margin-right: 6px !important;
    }
  }
}

// 主机列表对话框样式
.hostname-cell {
  display: flex;
  align-items: center;
}

.status-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;

  &.online {
    background-color: #67c23a;
    box-shadow: 0 0 6px rgba(103, 194, 58, 0.6);
  }

  &.offline {
    background-color: #f56c6c;
    box-shadow: 0 0 6px rgba(245, 108, 108, 0.6);
  }
}

.no-data {
  color: rgba(255, 255, 255, 0.5);
  font-style: italic;
}

/* 透明玻璃按钮样式 - 与角色管理页面保持一致，增加按钮大小 */
:deep(.glass-button.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
  border-radius: 8px !important;
  font-weight: 500 !important;

  /* 增加按钮大小和内边距 */
  padding: 8px 16px !important;
  min-width: 80px !important;
  height: 36px !important;
  font-size: 14px !important;

  /* 图标和文字间距 */
  i {
    margin-right: 6px !important;
  }

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
    color: #ffffff !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, rgba(0, 234, 255, 0.8), rgba(0, 153, 204, 0.8)) !important;
    border-color: rgba(0, 234, 255, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(51, 240, 255, 0.9), rgba(0, 184, 230, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }

  &.el-button--info {
    background: linear-gradient(135deg, rgba(108, 117, 125, 0.8), rgba(73, 80, 87, 0.8)) !important;
    border-color: rgba(108, 117, 125, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(130, 138, 145, 0.9), rgba(90, 98, 104, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4) !important;
    }
  }

  &.el-button--danger {
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.8), rgba(176, 42, 55, 0.8)) !important;
    border-color: rgba(220, 53, 69, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(240, 73, 89, 0.9), rgba(196, 62, 75, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(220, 53, 69, 0.4) !important;
    }
  }
}

/* 操作按钮容器样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

/* 页面下拉菜单样式 - 恢复透明样式但不设置深色背景 */
</style>
